package mbms.mobilebudget.exchangerateservice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import mbms.mobilebudget.entity.CurrencyRate;
import mbms.mobilebudget.entity.EnumValues.CurrencyType;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CurrencyRateParser {
	
	private static String RATE_TAG = "rate";
	private static String NAME_VALUE_TAG = "Name";
	private static String RATE_VALUE_TAG = "Rate";
	
	public CurrencyRateParser() {
	}
	
	public List<CurrencyRate> parseCurrencyRates(String uri) {
		List<CurrencyRate> currencyRateList = new ArrayList<CurrencyRate>();

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();

			Document dom = db.parse(uri);
			Element documentElement = dom.getDocumentElement();

			NodeList nl = documentElement.getElementsByTagName(RATE_TAG);
			if(nl != null && nl.getLength() > 0) {
				for(int i = 0 ; i < nl.getLength();i++) {
					Element el = (Element)nl.item(i);
					CurrencyRate currencyRate = getCurrencyRate(el);

					currencyRateList.add(currencyRate);
				}
			}

		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
		
		return currencyRateList;
	}
	
	private CurrencyRate getCurrencyRate(Element rateElement) {
		String name = getTextValue(rateElement, NAME_VALUE_TAG);
		
		String[] currencies = name.split(" ");
    	
		CurrencyType fromCurrency = CurrencyType.getCurrencyType(currencies[0]);
		CurrencyType toCurrency = CurrencyType.getCurrencyType(currencies[2]);
		
		Double rateValue = getDoubleValue(rateElement, RATE_VALUE_TAG);

		CurrencyRate rate = new CurrencyRate(fromCurrency, toCurrency, rateValue);

		return rate;
	}

	private String getTextValue(Element element, String tagName) {
		String textVal = null;
		NodeList nl = element.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}

	private Double getDoubleValue(Element element, String tagName) {
		return Double.parseDouble(getTextValue(element,tagName));
	}

}
